package it.valeandre.omino;

import it.valeandre.omino.db.DbAdapter;
import it.valeandre.omino.fragment.FeedsDetailFragment;
import it.valeandre.omino.fragment.FeedsFragment;
import it.valeandre.omino.fragment.OminoPagerFragment;
import it.valeandre.omino.fragment.SettingsSlidingFragment;
import it.valeandre.omino.fragment.SplashFragment;
import it.valeandre.omino.fragment.UpgradableBaseFragment;
import it.valeandre.omino.image.ImageDownloadService;
import it.valeandre.omino.model.Item;
import it.valeandre.omino.model.Match;
import it.valeandre.omino.model.Matches;
import it.valeandre.omino.model.RSS;
import it.valeandre.omino.model.Ranking;
import it.valeandre.omino.model.Results;
import it.valeandre.omino.model.Setting;
import it.valeandre.omino.model.TeamsList;
import it.valeandre.omino.net.NetworkService;
import it.valeandre.omino.net.NetworkServiceListener;
import it.valeandre.omino.utils.Config;
import it.valeandre.omino.utils.Maps;
import it.valeandre.omino.utils.MultiDirectionSlidingDrawer;
import it.valeandre.omino.utils.MultiDirectionSlidingDrawer.OnDrawerCloseListener;
import it.valeandre.omino.utils.MultiDirectionSlidingDrawer.OnDrawerOpenListener;
import it.valeandre.omino.utils.MyFragments;
import it.valeandre.omino.utils.NetworkObservable;
import it.valeandre.omino.utils.ResBundle;
import it.valeandre.omino.utils.ResizeAnimation;
import it.valeandre.omino.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;

import org.simpleframework.xml.core.Persister;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;

public class MainActivity extends BaseFragmentActivity {

	
	private static final boolean SHOW_FULLSCREEN_BANNER = true;
	public final static String KEY_GCM_TOKEN = "KEY_GCM_TOKEN";
	public final static String KEY_RANKING_LAST_DATE = "KEY_RANKING_LAST_DATE";
	public final static String GCM_PREFERENCES = "GCM_PREFERENCES";
	private ActivityReceiver mActivityReceiver;
	private LinearLayout mActionBarContainer;
	private ProgressDialog mProgressDialog;
	private TeamsList mTeams;
	private String mSettingTeamsString;
	private boolean mSettingPushFlag;
	private Ranking mRanking;
	private Results mResults;
	private Matches mMatches;
	private Matches mTmpMatches;
	private Results mTmpResults;
	private int mRequestCounter = 0;
	private HashMap<String, RSS> mTeamFeedCache;
	private NetworkObservable mRankingObservable;
	private NetworkObservable mResultsObservable;
	private NetworkObservable mTmpResultsObservable;
	private UpgradableBaseFragment mCurrentFragment;
	private MultiDirectionSlidingDrawer mSlider;
	private Setting mSettings;
	private boolean mGCMRegistrationError = true;
	private CountDownTimer mTimer;
	private ImageButton mRefreshButton;
	
	private InterstitialAd mFullScreenAd;
	private boolean mFullScreenRequestCompleted = false;
	private NetworkObservable mTeamsObservable;
	private UpgradableBaseFragment mSettingsFragment;
	private NetworkObservable mSettingsObservable;
	private boolean mRefreshPager = false;
	private NetworkObservable mTestTmpResultsObservable;
	private NetworkObservable mMatchesObservable;
	private NetworkObservable mTmpMatchesObservable;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try { 
			setContentView(R.layout.activity_main);
			
			if(ResBundle.URL_BASE.equals(ResBundle.URL_BASE_PROD)) {
				Utils.log("i", "******************** USING PROD BASE URL ********************");
				Utils.log("i", "******************** USING PROD BASE URL ********************");
				Utils.log("i", "******************** USING PROD BASE URL ********************");
				Utils.log("i", "******************** USING PROD BASE URL ********************");
			} else {
				Utils.log("w", "******************** USING TEST BASE URL ********************");
				Utils.log("w", "******************** USING TEST BASE URL ********************");
				Utils.log("w", "******************** USING TEST BASE URL ********************");
				Utils.log("w", "******************** USING TEST BASE URL ********************");
			}
			
			Utils.log("w", "*************************************************************************");
			Utils.log("w", "*************************************************************************");
			Utils.log("w", "*************************************************************************");
			Utils.log("w", "*************************************************************************");
			
			if(Utils.isLogEnabled()) {
				Utils.log("w", "******************** LOG IS ENABLED ********************");
				Utils.log("w", "******************** LOG IS ENABLED ********************");
				Utils.log("w", "******************** LOG IS ENABLED ********************");
				Utils.log("w", "******************** LOG IS ENABLED ********************");
			}
			
//			mRefreshPager = savedInstanceState.getBoolean(ResBundle.KEY_BUNDLE_FROM_MESSAGE_RECEIVED);
			mTeamFeedCache = new HashMap<String, RSS>();
			mHandler = new Handler();
			mSlider = (MultiDirectionSlidingDrawer) findViewById(R.id.slider);
			
			mActionBarContainer = (LinearLayout) findViewById(R.id.actionbar_container);
			ImageButton settings = (ImageButton) findViewById(R.id.settings_button);
			settings.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					if (mSlider.isOpened()) {
						mSlider.animateClose();
					} else {
						mSlider.animateOpen();
					}
				}
			});

            Button testButton = (Button) findViewById(R.id.test_button);
            testButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					createNotification(MainActivity.this, "Roma", "Inter", "2", "1", "", "Roma");
					
				}
//                @Override
//                public void onClick(View view) {
//                    createNotification(MainActivity.this, "Roma", "Inter", "2", "1", "", "Roma");
//                }
            });
            if(Config.BUILD_TYPE == Config.BUILD_TYPE_TEST) {
                testButton.setVisibility(View.VISIBLE);
            } else {
                testButton.setVisibility(View.GONE);
            }

			mRefreshButton = (ImageButton) findViewById(R.id.refresh_button);
			mRefreshButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					refreshCurrentPage();

				}
			});
			
			mSlider.setOnDrawerOpenListener(new OnDrawerOpenListener() {
				
				public void onDrawerOpened() {
					mRefreshButton.setEnabled(false);
//				if(mTeams == null) {
//					showProgress();
//					loadTeams(false);
//				}
					if(mSettings == null || isGCMRegistrationError()) {
						showProgress();
						loadSettings(false, new Observer() {
							
							public void update(Observable observable, Object data) {
								if (data != null) {
									register();
									if (mSettingsFragment != null) {

										mSettingsFragment.refresh();
									}
								}
								
							}
						});
					}
				}
			});
			mSlider.setOnDrawerCloseListener(new OnDrawerCloseListener() {
				
				public void onDrawerClosed() {
					mRefreshButton.setEnabled(true);
				}
			});
			
//			initBanners();
			if (SHOW_FULLSCREEN_BANNER) {
				initFullScreenBanner();
			}
			mActivityReceiver = new ActivityReceiver();
			IntentFilter filter = new IntentFilter(ResBundle.KEY_ACTION_MANAGE_REGISTERED);
			registerReceiver(mActivityReceiver, filter);

			switchToSplashFragment();
		} catch (Exception e) {
			showConnectionAlertDialog(new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					
					finish();
					
				}
			});
			
			e.printStackTrace();
		}

	}
	
	private void initFullScreenBanner() {
		mRequestCounter++;
		mFullScreenAd = new InterstitialAd(this, "a150db300344038");
	    AdRequest adRequest = new AdRequest();
	    HashSet<String> keyWords = new HashSet<String>();
		keyWords.add("Calcio");
		keyWords.add("Serie A");
		keyWords.add("Sport");
		keyWords.add("Classifica");
		adRequest.setKeywords(keyWords);
		adRequest.setGender(AdRequest.Gender.MALE);
	    
	    mFullScreenAd.loadAd(adRequest);

	    mFullScreenAd.setAdListener(new AdListener() {
			
			public void onReceiveAd(Ad ad) {
				Utils.log("i","FullScreenAd Received succesfully!");
				mFullScreenAd = (InterstitialAd) ad;
				mFullScreenRequestCompleted = true;
				manageRequestCounter(true);
			}
			
			public void onPresentScreen(Ad arg0) {
				mFullScreenRequestCompleted = true;
			}
			
			public void onLeaveApplication(Ad arg0) {
				mFullScreenRequestCompleted = true;
			}
			
			public void onFailedToReceiveAd(Ad arg0, ErrorCode code) {
				manageRequestCounter(true);
				mFullScreenRequestCompleted = true;
				if(code.equals(ErrorCode.INTERNAL_ERROR)) Utils.log("e", "FullScreenAd Error: INTERNAL_ERROR");
				else if(code.equals(ErrorCode.INVALID_REQUEST)) Utils.log("e","FullScreenAd Error: INVALID_REQUEST");
				else if(code.equals(ErrorCode.NETWORK_ERROR)) Utils.log("e","FullScreenAd Error: NETWORK_ERROR");
				else if(code.equals(ErrorCode.NO_FILL)) Utils.log("e","FullScreenAd Error: NO_FILL");
				else Utils.log("e","FullScreenAd Error: UNKNOWN");
			}
			
			public void onDismissScreen(Ad arg0) {
				mFullScreenRequestCompleted = true;
				showDisclaimer();
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		if(mSlider != null && mSlider.isOpened()) {
			mSlider.animateClose();
			if(mSettingsFragment != null) {
				((SettingsSlidingFragment)mSettingsFragment).undoUnsavedOperations();
			}
		} else {
			super.onBackPressed();
		}
		
	}
	
	public void register() {
		Utils.log("i", "@@@@@@@@@@@@@@@@@@@@ starting registration process...");
//		mRequestCounter++;
		
		Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
		intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		// Sender currently not used
		intent.putExtra("sender", "361433634449"); // mettere projectID anzicché
													// mail
		startService(intent);
		String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		Utils.log("i", "@@@@@@@@@@@@@@@@@@@@@    DEVICE ID = " + deviceId);
		
		mTimer = new CountDownTimer(7000, 1000) {
			
			@Override
			public void onTick(long millisUntilFinished) {
				
			}
			
			@Override
			public void onFinish() {
				Intent wakeUpActivityIntent = new Intent();
				wakeUpActivityIntent.setAction(ResBundle.KEY_ACTION_MANAGE_REGISTERED);
				wakeUpActivityIntent.putExtra(ResBundle.KEY_INTENT_TOKEN, "error");
				sendBroadcast(wakeUpActivityIntent);
			}
		};
		
		mTimer.start();
	}

	public void loadTeams(final boolean manageStartup, Observer observer) {
		Utils.log("i", "loadTeams...");
		mRequestCounter++;
		mTeamsObservable = new NetworkObservable();
		if (observer != null) {
			mTeamsObservable.addObserver(observer);
		}
		NetworkService.getInstance().getTeams(new NetworkServiceListener() {

			@Override
			public void getTeamsPerformed(final TeamsList teamsList) {
				Utils.log("d", "getTeamsPerformed");
				mTeams = teamsList;
				mTeamsObservable.notifyOperationPerformed(teamsList);
				manageRequestCounter(manageStartup);
			}

			@Override
			public void getTeamsFailed(int statusCode) {
				Utils.log("e", "getTeamsFailed " + statusCode);
				manageRequestCounter(manageStartup);
				mTeamsObservable.notifyOperationFailed();
			}

			@Override
			public void getTeamsFailed(Exception e) {
				Utils.log("e", "getTeamsFailed " + e.getMessage());
				manageRequestCounter(manageStartup);
				mTeamsObservable.notifyOperationFailed();
			}
		});
	}

	private class ActivityReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context ctx, Intent intent) {
			String token = intent.getStringExtra(ResBundle.KEY_INTENT_TOKEN);
			if (token.equals("error")) {
				Utils.log("GCM registration error");
				mGCMRegistrationError = true;
			} else {
				
				Utils.log("ActivityReceiver token received: " + token);
				mGCMRegistrationError = false;
				loadSettings(true, null);
			}
			if (mTimer != null) {
				mTimer.cancel();
			}
			if(mSettingsFragment != null) {
				mSettingsFragment.refresh();
			}
			
//			manageRequestCounter(true);
		}
	}

	private void initSettingsLayout() {
		UpgradableBaseFragment targetFragment = new SettingsSlidingFragment();
		mSettingsFragment = targetFragment;
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.slider_content, targetFragment, SettingsSlidingFragment.TAG);
		transaction.commit();
	}

	private void switchToSplashFragment() {
		UpgradableBaseFragment targetFragment = new SplashFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.content_view, targetFragment, SplashFragment.TAG);
		transaction.commit();

		mCurrentFragment = targetFragment;
	}

	private void switchToOminoFragment() {
		UpgradableBaseFragment targetFragment = new OminoPagerFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.content_view, targetFragment, OminoPagerFragment.TAG);
		transaction.commit();

		getSupportFragmentManager().executePendingTransactions();
		mCurrentFragment = targetFragment;
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mActivityReceiver);
		deleteRSAFiles();
		clearExecution();
		super.onDestroy();
	}
	
	@Override
	protected void onStop() {
		NetworkService.getInstance().shutdown();
		ImageDownloadService.getInstance().shutdown();
//		try {
//			unregisterReceiver(mActivityReceiver);
//		} catch (Exception e) {
//			e.printStackTrace();
//		} 
//		clearExecution();
		super.onStop();
	}

	public void expandActionBar() {
		try {
			int height = getResources().getDimensionPixelSize(R.dimen.action_bar_height);
			mActionBarContainer = (LinearLayout) findViewById(R.id.actionbar_container);
			ResizeAnimation animation = new ResizeAnimation(mActionBarContainer, mActionBarContainer.getWidth(), 0,
					mActionBarContainer.getWidth(), height);
			animation.setDuration(600);
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation arg0) {

				}

				public void onAnimationRepeat(Animation arg0) {

				}

				public void onAnimationStart(Animation arg0) {

				}

			});
			mActionBarContainer.startAnimation(animation);
		} catch (Exception e) {
			restartApp();
			e.printStackTrace();
		}

	}
	
	private void restartApp() {
		Intent intent = new Intent(MainActivity.this, MainActivity.class);
		finish();
		startActivity(intent);
	}

	public void hideActionBar() {
		ResizeAnimation animation = new ResizeAnimation(mActionBarContainer, mActionBarContainer.getWidth(), 0,
				mActionBarContainer.getWidth(), 1);
		// animation.setDuration(1500);
		animation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation arg0) {

			}

			public void onAnimationRepeat(Animation arg0) {

			}

			public void onAnimationStart(Animation arg0) {

			}

		});
		mActionBarContainer.startAnimation(animation);

	}

	public void showProgress() {
		mHandler.post(new Runnable() {
			
			public void run() {
				if (mProgressDialog == null) {
					mProgressDialog = ProgressDialog.show(MainActivity.this, "Attendere", "Caricamento in corso...", true, false);
				}
				
			}
		});
		

	}

	public void hideProgress() {
		mHandler.post(new Runnable() {
			
			public void run() {
				if (mProgressDialog != null && mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
					mProgressDialog = null;
				}
				
			}
		});
		

	}

	public TeamsList getTeams() {
		return mTeams;
	}

	public void setTeams(TeamsList mTeams) {
		this.mTeams = mTeams;
	}

	public void switchToFeedsFragment(String url) {
		UpgradableBaseFragment targetFragment = new FeedsFragment(url);
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.content_view, targetFragment, FeedsFragment.TAG);
		transaction.addToBackStack(FeedsFragment.TAG);
		transaction.commit();
		mCurrentFragment = targetFragment;

	}

	public void loadSettings(final boolean manageStartup, Observer observer) {
		Utils.log("i", "####################### loadSettings #######################");
		mRequestCounter++;
		mSettingsObservable = new NetworkObservable();
		if (observer != null) {
			mSettingsObservable.addObserver(observer);
		}
		mSettingTeamsString = null;
		mSettingPushFlag = false;
		String registrationId = Utils.readRegisteredToken(this);
		NetworkService.getInstance().getSettings(registrationId, new NetworkServiceListener() {

			@Override
			public void getSettingsPerformed(final Setting setting) {
				Utils.log("d", "getSettingsPerformed");
				Utils.log("d", "setting.getFlagPush(): " + setting.getFlagPush().getValue());
				Utils.log("d", "setting.getTeamsListString(): " + setting.getTeamsListString());
				Utils.log("d", "##########################################################################");
				mSettings = setting;
				mSettingTeamsString = setting.getTeamsListString();
				if (setting.getFlagPush().getValue().equals("false"))
					mSettingPushFlag = true;
				if (setting.getFlagPush().getValue().equals("true"))
					mSettingPushFlag = false;
				mHandler.post(new Runnable() {
					
					public void run() {
						mSettingsObservable.notifyOperationPerformed(setting);
						
					}
				});
				
				manageRequestCounter(manageStartup);
			}

			@Override
			public void getSettingsFailed(int statusCode) {
				Utils.log("e", "getSettingsFailed " + statusCode);
				manageRequestCounter(manageStartup);
				mHandler.post(new Runnable() {
					
					public void run() {
						mSettingsObservable.notifyOperationFailed();
						
					}
				});
				
//				showConnectionAlertDialogAsync();
			}

			@Override
			public void getSettingsFailed(Exception e) {
				Utils.log("e", "getSettingsFailed " + e.getMessage());
				manageRequestCounter(manageStartup);
				mHandler.post(new Runnable() {

					public void run() {
						mSettingsObservable.notifyOperationFailed();

					}
				});
//				showConnectionAlertDialogAsync();
			}
		});

	}

	public boolean getSettingPushFlag() {

		return mSettingPushFlag;
	}

	public void setSettingPushFlag(boolean flag) {

		mSettingPushFlag = flag;
	}

	public void loadTmpMatches(final boolean manageStartup, Observer observer) {
		Utils.log("i", "loadTmpResults...");
		mRequestCounter++;
		mTmpMatchesObservable = new NetworkObservable();
		if (observer != null) {
			mTmpMatchesObservable.addObserver(observer);
		}
		NetworkService.getInstance().getTmpResults(new NetworkServiceListener() {

//			@Override
//			public void getTmpResultsPerformed(final Results results) {
//				Utils.log("d", "Tmp Results object = " + results);
//				mTmpResults = results;
//				mTmpResultsObservable.notifyOperationPerformed(results);
//				manageRequestCounter(manageStartup);
//			}
			
			@Override
			public void getTmpResultsPerformed(final Matches matches) {
				Utils.log("d", "############################### Tmp Matches object = " + matches);
				mTmpMatches = matches;
				mTmpMatchesObservable.notifyOperationPerformed(matches);
				manageRequestCounter(manageStartup);
			}

			@Override
			public void getTmpResultsFailed(int statusCode) {
				Utils.log("e", "Tmp Matches error = " + statusCode);
				mTmpMatchesObservable.notifyOperationFailed();
				manageRequestCounter(manageStartup);
			}

			@Override
			public void getTmpResultsFailed(Exception e) {
				Utils.log("e", "Tmp Matches error = " + e.getMessage());
				mTmpMatchesObservable.notifyOperationFailed();
				manageRequestCounter(manageStartup);
			}

		});

	}
	
//	public void loadTestTmpResults(final boolean manageStartup, Observer observer) {
//		mRequestCounter++;
//		mTestTmpResultsObservable = new NetworkObservable();
//		if (observer != null) {
//			mTestTmpResultsObservable.addObserver(observer);
//		}
		
//		NetworkService.getInstance().getFromAssetsForTest(this, "xmlsoccerlive.xml", new NetworkServiceListener() {
//
//			@Override
//			public void getFromAssetsForTestTaskPerformed(Object obj) {
//				Matches matches = (Matches) obj;
//				for(Match m: matches.getMatchList()) {
//					Utils.log(m.getHometeam() + " - " + m.getAwayteam() + " .......... " + m.getHomeGoals() + " - " + m.getAwayGoals());
//				}
//			}
//			@Override
//			public void getFromAssetsForTestTaskFailed(Exception e) {
//				Utils.log("e", "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + "getFromAssetsForTestTaskFailed");
//				e.printStackTrace();
//			}
//			
//		});
		
//		NetworkService.getInstance().getTmpResults(new NetworkServiceListener() {
//
//			@Override
//			public void getTmpResultsPerformed(final Results results) {
//				Utils.log("d", "Tmp Results object = " + results);
//				mTmpResults = results;
//				mTestTmpResultsObservable.notifyOperationPerformed(results);
//				manageRequestCounter(manageStartup);
//			}
//
//			@Override
//			public void getTmpResultsFailed(int statusCode) {
//				Utils.log("e", "Tmp Results error = " + statusCode);
//				mTestTmpResultsObservable.notifyOperationFailed();
//				manageRequestCounter(manageStartup);
//			}
//
//			@Override
//			public void getTmpResultsFailed(Exception e) {
//				Utils.log("e", "Tmp Results error = " + e.getMessage());
//				mTestTmpResultsObservable.notifyOperationFailed();
//				manageRequestCounter(manageStartup);
//			}
//
//		});
//	}

	private void updateDbResults(final Results results) {
		mHandler.post(new Runnable() {

			public void run() {
				DbAdapter db = DbAdapter.getInstance(MainActivity.this);

				if (db.updateResults(results)) {
//					Toast.makeText(C2DMClientActivity.this, "db updated successfully", Toast.LENGTH_SHORT).show();
				} else {
//					Toast.makeText(C2DMClientActivity.this, "db updating error", Toast.LENGTH_SHORT).show();
				}

			}
		});

	}

	private Results getResultsFromDb() {
		DbAdapter db = DbAdapter.getInstance(this);
		return db.selectAllResults();
	}
	
	private Matches getMatchesFromDb() {
		DbAdapter db = DbAdapter.getInstance(this);
		return db.selectAllMatches();
	}

	public void loadResults(final boolean manageStartup, Observer observer) {
		Utils.log("i", "loadResults...");
		mRequestCounter++;
//		mResultsObservable = new NetworkObservable();
		mMatchesObservable = new NetworkObservable();
		if (observer != null) {
			mMatchesObservable.addObserver(observer);
		}
		NetworkService.getInstance().getResults(new NetworkServiceListener() {

//			@Override
//			public void getResultsPerformed(final Results results) {
//				Utils.log("d", "Results object = " + results);
//				mResults = results;
//				updateDbResults(results);
//				mResultsObservable.notifyOperationPerformed(results);
//				manageRequestCounter(manageStartup);
//			}
			@Override
			public void getResultsPerformed(final Matches matches) {
				Utils.log("d", "Matches object = " + matches);
				mMatches = matches;
				//TEST
				for(Match match: mMatches.getMatchList()) {
					Utils.log("HomeTeam = " + match.getHometeam());
					Utils.log("AwayTeam = " + match.getAwayteam());
				}
				//TEST END
//				updateDbResults(results);
				mMatchesObservable.notifyOperationPerformed(matches);
				manageRequestCounter(manageStartup);
			}

			@Override
			public void getResultsFailed(int statusCode) {
				Utils.log("e", "Matches error = " + statusCode);
				// carico dal db.. e faccio notifyOperationPerformed
				// se results è null faccio notifyOperationFailed
				mMatches = getMatchesFromDb();
				if (mMatches != null && mMatches.getMatchList() != null && mMatches.getMatchList().size() > 0) {
					mMatchesObservable.notifyOperationPerformed(mMatches);
				} else {
					mMatchesObservable.notifyOperationFailed();
				}

				manageRequestCounter(manageStartup);
			}

			@Override
			public void getResultsFailed(Exception e) {
				Utils.log("e", "Matches error = " + e.getMessage());
//				mMatches = getMatchesFromDb();
				if (mMatches != null && mMatches.getMatchList().size() > 0) {
					mMatchesObservable.notifyOperationPerformed(mMatches);
				} else {
					mMatchesObservable.notifyOperationFailed();
				}
				manageRequestCounter(manageStartup);
			}

		});

	}

	private Ranking getSavedRanking() {
		Ranking ranking = null;
		String FILENAME = ResBundle.RES_RANKING_FILE_NAME;

		FileInputStream fis;
		Persister serializer = new Persister();
		try {
			fis = openFileInput(FILENAME);
			ranking = serializer.read(Ranking.class, fis, false);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ranking;
	}

	private boolean saveRanking(String html) {
		boolean ret = false;
		String FILENAME = ResBundle.RES_RANKING_FILE_NAME;
		// String html = "hello world!";

		FileOutputStream fos;
		try {
			fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
			fos.write(html.getBytes());
			fos.close();
			ret = true;
			mHandler.post(new Runnable() {

				public void run() {
//					Toast.makeText(C2DMClientActivity.this, "ranking saved successfully", Toast.LENGTH_SHORT).show();

				}
			});

		} catch (FileNotFoundException e) {
			mHandler.post(new Runnable() {

				public void run() {
//					Toast.makeText(C2DMClientActivity.this, "error saving ranking", Toast.LENGTH_SHORT).show();

				}
			});

			e.printStackTrace();
		} catch (IOException e) {
			mHandler.post(new Runnable() {

				public void run() {
//					Toast.makeText(C2DMClientActivity.this, "error saving ranking", Toast.LENGTH_SHORT).show();

				}
			});
			e.printStackTrace();
		}

		return ret;

	}

	public void loadRanking(final boolean manageStratup, Observer observer) {
		mRequestCounter++;
		mRankingObservable = new NetworkObservable();
		if (observer != null) {
			mRankingObservable.addObserver(observer);
		}
		NetworkService.getInstance().getRanking(new NetworkServiceListener() {

			@Override
			public void getRankingPerformed(final Ranking ranking, final String html) {
				Utils.log("d", "Ranking object = " + ranking);
				mRanking = ranking;
				Utils.saveRankingLastDate(MainActivity.this, System.currentTimeMillis());
				saveRanking(html);
				mRankingObservable.notifyOperationPerformed(ranking);
				manageRequestCounter(manageStratup);
			}

			@Override
			public void getRankingFailed(int statusCode) {
				Utils.log("e", "Ranking error = " + statusCode);
				mRanking = getSavedRanking();
				if (mRanking != null && mRanking.rows.size() > 0 && mRanking.rows.size() > 0) {
					mRankingObservable.notifyOperationPerformed(mRanking);
				} else {
					mRankingObservable.notifyOperationFailed();
				}
				manageRequestCounter(manageStratup);
			}

			@Override
			public void getRankingFailed(Exception e) {
				Utils.log("e", "Ranking error = " + e.getMessage());
				mRanking = getSavedRanking();
				if (mRanking != null && mRanking.rows.size() > 0 && mRanking.rows.size() > 0) {
					mRankingObservable.notifyOperationPerformed(mRanking);
				} else {
					mRankingObservable.notifyOperationFailed();
				}
				manageRequestCounter(manageStratup);
				e.printStackTrace();
			}

		});

	}

	public Ranking getRanking() {
		return mRanking;
	}

	public Results getResults() {
		return mResults;
	}

	public Matches getTmpResults() {
		return mTmpMatches;
	}

	private void manageRequestCounter(boolean manageStartup) {
		mRequestCounter--;
		Utils.log("i", "feeds remaining = " + mRequestCounter);
		if (mRequestCounter == 0) {
			hideProgress();
			if (manageStartup) {
				mHandler.post(new Runnable() {
					public void run() {
						if (isActivityUp) {
							notifyLoadFeedPerformed();
						}
					}
				});
			}

		}
	}

	public void notifyLoadFeedPerformed() {
		//SHOW FULLSCREEN AD
		
		if(mFullScreenRequestCompleted && SHOW_FULLSCREEN_BANNER /*&& mFullScreenAdReceived == mFullScreenAd */) {
			mFullScreenAd.show();
		}
		
		initSettingsLayout();
		initBanners();
		switchToOminoFragment();
		
		if (!SHOW_FULLSCREEN_BANNER) {
			showDisclaimer();
		}
		
		
	}
	
	private void showDisclaimer() {
		if(Config.SHOW_DISCLAIMER && Utils.readShowDisclaimer(this)) {
			mHandler.post(new Runnable() {
				
				public void run() {
					showDisclaimerDialog();
					
				}
			});
			
		}
	}

	public void switchToFeedDetailFragment(Item feed) {
		UpgradableBaseFragment targetfragment = new FeedsDetailFragment(feed);
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.content_view, targetfragment, FeedsDetailFragment.TAG);
		transaction.addToBackStack(FeedsDetailFragment.TAG);
		transaction.commit();
		mCurrentFragment = targetfragment;

	}

	public void updateTeamFeeds(String url, RSS feeds) {
		mTeamFeedCache.put(url, feeds);
	}

	public RSS getTeamFeeds(String url) {
		return mTeamFeedCache.get(url);
	}

	@Override
	protected void refreshCurrentPage() {
		mCurrentFragment.refresh();
	}

	public void showDialog(String message) {
		showAlertDialogAsync(new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

			}
		}, getResources().getString(R.string.warning), message);

	}

	public void showDialog(String message, android.content.DialogInterface.OnClickListener positiveListener) {
		showAlertDialogAsync(positiveListener, getResources().getString(R.string.warning), message);

	}

	public MultiDirectionSlidingDrawer getSlider() {
		return mSlider;
	}

	public void performBack() {
		super.onBackPressed();

	}

	public boolean isGCMRegistrationError() {
		return mGCMRegistrationError;
	}

	public ImageButton getRefreshImageButton() {
		return mRefreshButton;
	}

	public void setCurrentFragment(UpgradableBaseFragment fragment) {
		mCurrentFragment = fragment;
		
	}
	
	private void clearExecution() {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction ft = fragmentManager.beginTransaction();

		Fragment fragment;
		for (String tag : MyFragments.TAGS) {
			fragment = fragmentManager.findFragmentByTag(tag);
			if (fragment != null) {
				ft.remove(fragment);
			}
		}
		ft.commitAllowingStateLoss();

	}
	
	public void deleteRSAFiles() {
		String sdcard = Environment.getExternalStorageDirectory() + "/RSA/";
		File fileList = new File(sdcard);

		if (fileList != null) { // check if dir is not null
			File[] filenames = fileList.listFiles();

			if (filenames != null) {
				for (File tmpf : filenames) {
					if (tmpf != null) {
						tmpf.delete();
					}
				}
			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent); 
		if (intent != null && intent.getExtras() != null) {
			mRefreshPager = intent.getExtras().getBoolean(ResBundle.KEY_BUNDLE_FROM_MESSAGE_RECEIVED);
			
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(mCurrentFragment != null && mCurrentFragment instanceof OminoPagerFragment && mRefreshPager) {
			((OminoPagerFragment) mCurrentFragment).refreshAll();
		}
		String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		Utils.log("i", "##########################################################################");
		Utils.log("i", "device id = " + deviceId);
		Utils.log("i", "token = " + Utils.readRegisteredToken(this));
		Utils.log("i", "##########################################################################");
	}
	
	public Setting getSettings() {
		return mSettings;
		
	}

	public String getSettingTeamsString() {
		return mSettingTeamsString;
	}

	public Matches getMatches() {
		return mMatches;
	}

	public void setMatches(Matches mMatches) {
		this.mMatches = mMatches;
	}

    public void createNotification(Context context, String hometeam, String awayteam, String homegoal, String awaygoal, String details, String team) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = createNotificationWithIcon(team);
        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        Intent intent = new Intent(context, EventReceivedActivity.class);
        intent.putExtra("hometeam", hometeam);
        intent.putExtra("awayteam", awayteam);
        intent.putExtra("homegoal", homegoal);
        intent.putExtra("awaygoal", awaygoal);
        intent.putExtra("goalDetails", details);
        intent.putExtra("teamGoal", team);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, Calendar.getInstance().get(Calendar.MILLISECOND), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        String info = hometeam + " - " + awayteam + "   " + homegoal + " - " + awaygoal;

        notification.defaults |= Notification.DEFAULT_SOUND;

        notification.defaults |= Notification.DEFAULT_VIBRATE;

        String notificationTitle;
        if(team != null && !team.trim().equals("")) {
            notificationTitle = "Goal, " + team;
            int id = (hometeam + awayteam).hashCode();
            notification.setLatestEventInfo(context, notificationTitle, info, pendingIntent);
            notificationManager.notify(id, notification);
        }

    }

    public Notification createNotificationWithIcon(String team) {

        Notification notification = new Notification(R.drawable.palla_calcio, "Evento partita", System.currentTimeMillis());

        for(String keyTeam: Maps.TEAM_LOGO_SMALL_MAP.keySet()) {
            try {
                if(team != null && team.contains(keyTeam)) {
                    notification = new Notification(Maps.TEAM_LOGO_SMALL_MAP.get(keyTeam), "Ha segnato: " + keyTeam, System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return notification;
    }

}